import {
    Component, ChangeDetectionStrategy, Input,
    ChangeDetectorRef, OnInit, Inject, forwardRef
} from '@angular/core';
import { AccordionConfig } from 'ngx-bootstrap/accordion';
import { Router } from '@angular/router';

import { TabDirective } from '../../lib/tab-directive';
import { masterService } from '../../lib/master.service'

import { GoodsMarkingComponent } from './goods-management/goods-marklist/goods-marking/goods-marking.component';

import { ActivityGoodsManagementModalComponent } from './campaign-management/activity-goods-management/activity-goods-management-modal/activity-goods-management-modal.component';
import { ActivityGoodsManagementAddModalComponent } from './campaign-management/activity-goods-management/activity-goods-management-add-modal/activity-goods-management-add-modal.component';

import { ClickOrderActivityAddComponent } from './campaign-management/click-order-activity-management/click-order-activity-add/click-order-activity-add.component';
import { ClickOrderActivityEditComponent } from './campaign-management/click-order-activity-management/click-order-activity-edit/click-order-activity-edit.component';
import { LeadDownloadActivityAddComponent } from './campaign-management/lead-download-activity-management/lead-download-activity-add/lead-download-activity-add.component';
import { LeadDownloadActivityEditComponent } from './campaign-management/lead-download-activity-management/lead-download-activity-edit/lead-download-activity-edit.component';
import { ExchangeCardAddComponent } from './exchange-card-management/exchange-card-management/exchange-card-add/exchange-card-add.component';
import { ExchangeCardTemplateAddComponent } from './exchange-card-management/exchange-card-template-management/exchange-card-template-add/exchange-card-template-add.component';
import { ExchangeCardTemplateEditComponent } from './exchange-card-management/exchange-card-template-management/exchange-card-template-edit/exchange-card-template-edit.component';

import { menu } from '../menu.config';

export function getAccordionConfig(): AccordionConfig {
    return Object.assign(new AccordionConfig(), { closeOthers: true });
}

@Component({
    selector: 'cms-root',
    //输入属性没有变化，跳过对该组件的全部变化检测
    changeDetection: ChangeDetectionStrategy.OnPush,
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.css'],
    providers: [{ provide: AccordionConfig, useFactory: getAccordionConfig },
    forwardRef(() => TabDirective)
    ]
})

export class HomeComponent implements OnInit {
    public username: any;
    public Data: any;
    private removable: boolean;
    public disabled: boolean;

    @Input() tabs;
    constructor(public cdRef: ChangeDetectorRef,
        @Inject(forwardRef(() => TabDirective)) public TabDirective: TabDirective,
        private _masterService: masterService,
        private _router: Router) {
        // 菜单名字数据
        this.Data = menu;
        this.disabled = true;
        this.tabs = [];
    }

    ngOnInit() {
        // 重载页面token验证
        if (localStorage.getItem("expires")) {
            let time = localStorage.getItem("expires");
            let now = new Date().getTime();
            if (now - Number(time) >= 86400 * 1000) {
                this._router.navigate(['/login']);
                localStorage.clear();
                return;
            }
        } else {
            this._router.navigate(['/login']);
            localStorage.clear();
            return;
        }
        this.initSubscribe();
        this.initTabs();
        this.username = localStorage.getItem("alias");
        this.cdRef.detectChanges();
    }

    // 增添tab
    addTab = (tabRef, firstMenu): void => {
        firstMenu.active = false;
        // 在数组tabs中遍历tab
        for (const tab of this.tabs) {
            // 如果传入的对象与tabs数组中的对象相同
            if (tabRef.name === tab.name) {
                // tab激活，已存在
                tab.active = true;
                tabRef.tabExist = true;
                firstMenu.active = true;
            } else {
                // tab失效
                tab.active = false;
                firstMenu.active = false;
            }
        }
        // 如果tab不存在
        if (!tabRef.tabExist) {
            // 激活，加入tabs数组
            tabRef.active = true;
            tabRef.tabExist = true;
            firstMenu.active = true;
            this.tabs.push(tabRef);
        }
        let tabs_status = JSON.stringify(this.tabs)
        localStorage.setItem('tabs_status', tabs_status);
        // 更新dom节点
        this.cdRef.detectChanges();
    }

    // 移除右边选项卡即从数组中移除
    removeTabHandler(tab, i?): void {
        // 删除选项卡时改变菜单对应选项卡的状态
        let curData = this.Data;
        curData.forEach((v, i) => {
            let curSecondMenu = curData[i].secondMenu;
            curSecondMenu.forEach((v, j) => {
                if (curSecondMenu[j].name === tab.name) {
                    curSecondMenu[j].tabExist = false;
                    curSecondMenu[j].active = false;
                }
            })
        })
        var index = this.tabs.indexOf(tab);
        // 定义当前tab的下标
        if (i) {
            index = i
        }
        // 从tabs数组中删除tab
        this.tabs.splice(index, 1);
        // tabs不为空且当前tab存在时
        if (this.tabs.length > 0 && tab.active) {
            // tabs最后一个tab激活
            this.tabs[this.tabs.length - 1].active = true;
        }
        let tabs_status = JSON.stringify(this.tabs)
        localStorage.setItem('tabs_status', tabs_status);
    }

    // 点击选项卡控制左边菜单激活
    activateNav(tab) {
        tab.active = true;
        let curData = this.Data;
        curData.forEach((v, i) => {
            let curSecondMenu = curData[i].secondMenu;
            for (let j = 0; j < curSecondMenu.length; j++) {
                if (tab.name === curSecondMenu[j].name) {
                    // 选中的tab与data中的二级菜单比较，如果相同就把激活状态付给当前一级菜单的激活状态，跳出当前二级菜单的循环
                    curData[i].firstMenu.active = tab.active;
                    break;
                } else {
                    curData[i].firstMenu.active = !tab.active;
                }
            }
        })
    }

    // 登出
    logOff() {
        localStorage.clear();
        this._router.navigate(['/login']);
    }

    // 订阅打开、关闭tab选项卡事件
    initSubscribe() {
        // 订阅打开新建商品标签
        this._masterService.createMarkList.subscribe((val) => {
            this.addTab({ 'name': '新建商品标签', 'componentClass': GoodsMarkingComponent }, { 'name': '商品标签管理' });
        })

        // 订阅打开活动商品
        this._masterService.openActivity.subscribe((val) => {
            if (val) {
                this.addTab({ 'name': '活动商品设置', 'componentClass': ActivityGoodsManagementModalComponent }, { 'name': '市场活动管理' })
                this.cdRef.detectChanges();
            } else {
                this.addTab({ 'name': '活动商品新增', 'componentClass': ActivityGoodsManagementAddModalComponent }, { 'name': '市场活动管理' })
                this.cdRef.detectChanges();
            }
        })

        // 订阅保存后关闭活动商品
        this._masterService.closeActivity.subscribe((id) => {
            if (id) {
                this.tabs.forEach((v, i) => {
                    if (v.name == '活动商品设置') {
                        let index = i;
                        this.removeTabHandler({ 'name': '活动商品设置', 'active': false, 'tabExist': true, 'componentClass': ActivityGoodsManagementModalComponent }, index);
                        this.tabs[this.tabs.length - 1].active = true;
                    }
                })
            } else {
                this.tabs.forEach((v, i) => {
                    if (v.name == '活动商品新增') {
                        let index = i;
                        this.removeTabHandler({ 'name': '活动商品新增', 'active': false, 'tabExist': true, 'componentClass': ActivityGoodsManagementModalComponent }, index);
                        this.tabs[this.tabs.length - 1].active = true;
                    }
                })
            }
            this.cdRef.detectChanges();
        })

        // 订阅打开一键下单
        this._masterService.openClickOrder.subscribe((val) => {
            if (val) {
                this.addTab({ 'name': '活动设置', 'componentClass': ClickOrderActivityEditComponent }, { 'name': '市场活动管理' })
                this.cdRef.detectChanges();
            } else {
                this.addTab({ 'name': '活动新增', 'componentClass': ClickOrderActivityAddComponent }, { 'name': '市场活动管理' })
                this.cdRef.detectChanges();
            }
        })

        // 订阅打开引导下载
        this._masterService.openLeadDownload.subscribe((val) => {
            if (val) {
                this.addTab({ 'name': '引导下载活动编辑', 'componentClass': LeadDownloadActivityEditComponent }, { 'name': '市场活动管理' })
                this.cdRef.detectChanges();
            } else {
                this.addTab({ 'name': '引导下载活动新增', 'componentClass': LeadDownloadActivityAddComponent }, { 'name': '市场活动管理' })
                this.cdRef.detectChanges();
            }
        })

        // 订阅打开卡券模板设置
        this._masterService.openCardTemplate.subscribe((val) => {
            if (val) {
                this.addTab({ 'name': '卡券模板修改', 'componentClass': ExchangeCardTemplateEditComponent }, { 'name': '卡券模板管理' })
                this.cdRef.detectChanges();
            } else {
                this.addTab({ 'name': '卡券模板新增', 'componentClass': ExchangeCardTemplateAddComponent }, { 'name': '卡券模板管理' })
                this.cdRef.detectChanges();
            }
        })

        // 订阅保存后关闭活动商品
        this._masterService.closeCardTemplate.subscribe((id) => {
            if (id) {
                this.tabs.forEach((v, i) => {
                    if (v.name == '卡券模板修改') {
                        let index = i;
                        this.removeTabHandler({ 'name': '活动商品设置', 'active': false, 'tabExist': true, 'componentClass': ExchangeCardTemplateEditComponent }, index);
                        this.tabs[this.tabs.length - 1].active = true;
                    }
                })
            } else {
                this.tabs.forEach((v, i) => {
                    if (v.name == '卡券模板新增') {
                        let index = i;
                        this.removeTabHandler({ 'name': '活动商品新增', 'active': false, 'tabExist': true, 'componentClass': ExchangeCardTemplateAddComponent }, index);
                        this.tabs[this.tabs.length - 1].active = true;
                    }
                })
            }
            this.cdRef.detectChanges();
        })

        // 订阅打开新建生成卡券批次
        this._masterService.openCardBatchinfo.subscribe((val) => {
            if (val) {
                this.addTab({ 'name': '新建领卡批次', 'componentClass': ExchangeCardAddComponent }, { 'name': '新建领卡批次' })
                this.cdRef.detectChanges();
            } else {
                this.addTab({ 'name': '新建领卡批次', 'componentClass': ExchangeCardAddComponent }, { 'name': '新建领卡批次' })
                this.cdRef.detectChanges();
            }
        })
    }

    // 保存刷新之前的tab
    initTabs() {
        if (localStorage.getItem('tabs_status')) {
            // 将localstorage中的tabs_status转换为js对象
            let tabs_status = JSON.parse(localStorage.getItem('tabs_status'));
            // 根据storage保存的数据匹配出需要渲染的component
            tabs_status.forEach((tabVal, index) => {
                for (let i = 0; i < menu.length; i++) {
                    let secondMenu = menu[i].secondMenu;
                    for (let j = 0; j < secondMenu.length; j++) {
                        if (secondMenu[j].name == tabVal.name) {
                            tabVal.tabExist = false;
                            this.addTab(secondMenu[j], menu[i].firstMenu);
                        }
                    }
                }
            })
        }
    }
}

